﻿using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel;
using Alipay.EasySDK.Kernel.Util;
using Alipay.EasySDK.Payment.FaceToFace.Models;
using Alipay.EasySDK.Payment.Page.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using LiveShopvnext.CommoditySpecificas;
using Volo.Abp.Domain.Repositories;
using LiveShopvnext.Commods;
using LiveShopvnext.CommodOrders;

namespace LiveShopvnext.Pay
{
    public class ALiPayAppService : ApplicationService, IALiPayAppService
    {
        private readonly IHttpContextAccessor _contextAccessor;
        private readonly IRepository<CommodOrder, Guid> _repository3;
        public ALiPayAppService(IHttpContextAccessor contextAccessor, IRepository<CommodOrder, Guid> repository3)
        {
            _repository3 = repository3;
_contextAccessor = contextAccessor;
        }
        [HttpGet]
        //直接测试用地址,记得改订单信息. https://localhost:44341/api/app/a-li-pay/pay?Subject=test1&outTradeNo=111111111112&totalAmount=500
        public async void Pay(PayDto dto)
        {
            #region 1. 设置参数（全局只需设置一次）
            var config = new Config()
            {
                Protocol = "https",
                GatewayHost = "openapi.alipaydev.com",//"openapi.alipay.com",沙箱
                SignType = "RSA2",
                AppId = "2021000118636011",
                //请填写您的应用私钥
                MerchantPrivateKey = "MIIEogIBAAKCAQEAuDuwYEL9FQVhzMvtBrz35YbB3h7hZlVvf/m74RPKjAaINQscj8rZ2QrqaiP/lUam9xmXssMZN8OT3d2YhsDImvACGB/nfEDcFk1i9FtdENigEm8DVDk6wySvdDxvf1plVuJK6DzBwu/mgVNXhG2gg+lG06hFAOtBf8weetTID7hEEsm3WDcESUzDszBQUpCNUoF67ts+9EsMyJzyg0aWE9mH9tAmS5eVGVJ3pec3FmENKhtMA6Wh9nlI5zoKIrhwvgJU2csbcfk0+ZngcXP8LvbgpPL8vGrSJrSndXwyaDD0Tku+9dncimN8xN+SUuNIZIBb3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yHleGJImMGnfD1iYFP04QBQTaNJ68m0PFy11kHNTPjX0RNUYFLg/C3XdGeGJmgH76ROfNJKdCtO4d/qyACxYBZHTGiLBDZ3oJce5Nw27SgG73GGvs5bI5LqP8pcJYhQ+DhZCp7tm0enp3RkS5eqTlAUXLOA=",
                //支付宝公钥
                AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjKRLLsD6riNIrJA/qVhs35/90k+pgPrzTdOsuEq61vOxDurFuE0dN2tneNIIn0TIPOF1hgGamflOR47WViWKWVFGjbaRJMcDMxTq26EBD7ehzV8cDQ4SL8u9RRUmCHDKmXiZs2PB0kJIJnRuWrcsMkcoBL5WaH97opxa3eKp70CIvzG+pbBSx9qY8AcLrAcKqls854mDcHP0eN8L9N1EH6pZiydDwhNzIUQ7+uG6nbO+LA9RzIJp90w1Jj4StqrP6hPsUjN6yMcRbH0wFf3XrIbIQ7aZQOE0p70kKw8/GdmKno6lOsIdYtClra4V3dj+TCHFdqouSCVET+9tlg1uUwIDAQAB",
                //异步回调地址
                NotifyUrl = "https://localhost:44341/api/app/a-li-pay/notify-url",
                // NotifyUrl = "https://localhost:44341/api/app/a-li-pay/notify-url",
                
            };
            Factory.SetOptions(config);
            #endregion
            try
            {
                // 2. 发起API调用（以创建当面付收款二维码为例）
                //TODO:实训标题和订单号及金额是从dto中取得
                AlipayTradePagePayResponse response = Factory.Payment.Page().Pay(dto.Subject, dto.outTradeNo, dto.totalAmount, "https://localhost:44341/api/app/a-li-pay/return-url");
                // 3. 处理响应或异常
                if (ResponseChecker.Success(response))
                {
                    
                    //把返回的html直接变成网页显示
                    var data = Encoding.UTF8.GetBytes(response.Body);
                    _contextAccessor.HttpContext.Response.ContentType = "text/html";
                    await _contextAccessor.HttpContext.Response.Body.WriteAsync(data, 0, data.Length);
                }
                else
                {
                    Console.WriteLine("调用失败，原因：" + response.Body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("调用遭遇异常，原因：" + ex.Message);
            }
        }
        




        [HttpGet]
        public async Task<string> ReturnUrlAsync(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                var ml= FreeActionAppService.ml;
                Guid k = _repository3.Where(s => s.OrderInfoWaybillNum == ml.ToString()).ToList()[0].Id;
               
                var dic =await  _repository3.GetAsync(k);
                dic.OrderInfoState =(OrderInfoStateEnum)20;

                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //if()先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update

                return "success";
            }
            return "";
        }

        [HttpGet]
        public string NotifyUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update
                //再循环返回库存
                //update


                return "success";
            }
            return "";
        }

        string IALiPayAppService.ReturnUrlAsync(PayReturnDto dto)
        {
            throw new NotImplementedException();
        }
    }
}